package com.kaikeba.controller;

import com.kaikeba.bean.Student;
import com.kaikeba.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class StudentController {

    @Autowired
    @Qualifier(value = "studentServiceImpl")
    private StudentService studentService;


    @RequestMapping("addstudnet")
    public String addstudnet(Student student){
        int i = studentService.insertSelective(student);
        if (i>0){
            return "redirect:/mainpage";
        }else {
            return "redirect:/addpage";
        }

    }


    @RequestMapping("update")
    public String update(Integer stuid, Model model){
        Student student = studentService.selectByPrimaryKey(stuid);
        switch (student.getGradeid()){
            case 1:
                model.addAttribute("flag",1);
                break;
            case 2:
                model.addAttribute("flag",2);
                break;
            case 3:
                model.addAttribute("flag",3);
                break;
        }
        model.addAttribute("student",student);
        return "update";
    }

    @RequestMapping("updates")
    public String updates(Student student){
        int i = studentService.updateByPrimaryKeySelective(student);
        if (i>0){
            return "redirect:/mainpage";
        }else {
            return "redirect:/update";
        }
    }

    @RequestMapping("/delete")
    public void delete(Integer stuid, HttpServletResponse response){
        int i = studentService.deleteByPrimaryKey(stuid);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            if (i>0){
                writer.print("<script>alert('删除成功');location.href='/mainpage' </script>");
            }else {
                writer.print("<script>alert('删除失败');location.href='/mainpage' </script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
